package org.aphelie.romancer.model.editor;

import java.io.File;
import java.net.URI;

import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;

public final class RomancerResourceHelper {
	
	private RomancerResourceHelper() {
	}
	
	private static final IProgressMonitor MONITOR = new NullProgressMonitor();
	
	
	public static IPath getLocation(IResource resource) {
		File localFile = getLocalFile(resource);
		IPath path = null;
		if (localFile != null) {
			path = new Path(localFile.getAbsolutePath());
		}
		if (! path.equals(resource.getFullPath())) {
			System.err.println("IPath getLocation(IResource resource) TODO" );
		}
		
		return path;
	}
	
	
	public static File getLocalFile(IResource resource) {
		if (resource == null) {
			return null;
		}
		return getLocalFile(resource.getLocationURI());
	}
	
	private static File getLocalFile(URI locationURI) {
		if (locationURI == null) {
			return null;
		}
		try {
			IFileStore store = EFS.getStore(locationURI);
			File file = store.toLocalFile(EFS.NONE, MONITOR);
			if (file == null) {
				file = store.toLocalFile(EFS.CACHE, MONITOR);
			}
			return file;
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	

}
